package com.qf.controller;

/**
 * @author sunyamei
 * @version V1.0
 * @Project javase2203
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/8/16 10:42
 */

import com.qf.utils.RedisLockUtil;
import com.sun.scenario.Settings;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 模拟高并发秒杀
 */
@RestController
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    private CuratorFramework cf;

    @Autowired
    private RedisLockUtil redisLockUtil;

    //1. 准备全局变量库存
    public static Map<String, Integer> itemStock = new HashMap<>();

    //2. 准备全局变量订单
    public static Map<String, Integer> itemOrder = new HashMap<>();

    //3. 初始化库存量和订单量
    static {
        itemStock.put("牙刷", 10000);
        itemOrder.put("牙刷", 0);
    }

    /**
     * 模拟秒杀下单
     * @param key
     * @return
     */
    @GetMapping("/kill")
    public String seckill(String key) throws Exception {

        //====================创建zookeeper锁对象=====================
        //InterProcessMutex lock = new InterProcessMutex(cf, "/lock");
        //====================zookeeper加锁=========================
        //if (lock.acquire(1, TimeUnit.SECONDS)) {

        //====================redis加锁========================
        if (redisLockUtil.lock("lock", "1", 1)) {

            //1. 扣减库存
            Integer stock = itemStock.get(key);
            if (stock < 0) {
                return "库存不足, 不允许下单!";
            }
            itemStock.put(key, stock - 1);

            Thread.sleep(100);

            //2. 下单
            itemOrder.put(key, itemOrder.get(key) + 1);

            //=====================zookeeper解锁=========================
            //lock.release();

            //====================redis解锁================================
            redisLockUtil.unlock("lock");

            //3. 返回信息, 当前库存量, 当前订单量
            return "下单完成: 库存量:" + itemStock.get(key) + ", 订单量:"+itemOrder.get(key);
        } else {
            return "不好意思, 您没有抢到!!!";
        }



    }


}